package com.example.nonggo.view.act;

import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.allen.library.RxHttpUtils;
import com.allen.library.interceptor.Transformer;
import com.example.nonggo.Constants;
import com.example.nonggo.R;
import com.example.nonggo.api.BaseApi;
import com.example.nonggo.api.MDataObserver;
import com.example.nonggo.bean.AiWeatherRes;
import com.example.nonggo.contract.QuestionContract;
import com.tencent.mmkv.MMKV;

import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;

import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

import io.noties.markwon.Markwon;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;

import static android.view.View.GONE;
import static android.view.View.VISIBLE;

public class AiWeatherActivity extends AppCompatActivity {

    public final String token =  MMKV.defaultMMKV().getString(Constants.ACCESS_TOKEN,"0");
    public final String city =  MMKV.defaultMMKV().getString(Constants.CITY,"广州市");
    public final String county =  MMKV.defaultMMKV().getString(Constants.COUNTY,"天河区");
    public final String user =  MMKV.defaultMMKV().getString(Constants.MOBILE,"0");
    public final String province =  MMKV.defaultMMKV().getString(Constants.PROVINCE,"广东省");
    private ArrayList<String> cropList;
    private Spinner cropSpinner;
    private TextView content;
    private TextView tvLoad;
    final int count = 60;
    private Markwon markwon;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        getWindow().setNavigationBarColor(Color.TRANSPARENT);
        // 隐藏状态栏
        getWindow().getDecorView().setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
        setContentView(R.layout.activity_ai_weather);
         tvLoad = findViewById(R.id.tv_load);
        // 初始化数据源
        cropList = new ArrayList<>();
        cropList.add("水稻");
        cropList.add("蝴蝶兰");
        cropList.add("水产");
        cropList.add("桃花");
        cropList.add("青梅");
        cropList.add("玉米");
        cropList.add("绿萝");
        cropList.add("甘薯");
        cropList.add("花生");
        cropList.add("蔬菜");
        cropSpinner = findViewById(R.id.spinner);
        content = findViewById(R.id.tv_content);
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
                R.layout.custom_spinner_item,  R.id.tv_item, cropList);
        adapter.setDropDownViewResource(R.layout.custom_spinner_item);
        cropSpinner.setAdapter(adapter);
        // 添加Spinner的弹出监听
        cropSpinner.setOnTouchListener((v, event) -> {
            // 在Spinner弹出时保持全屏状态
            getWindow().getDecorView().setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
            return false;
        });
        // 构建 Markwon 实例（需添加 Glide 依赖）
          markwon = Markwon.builder(this)
                .build();
        // 设置选择事件监听
        cropSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String selectedCrop = cropList.get(position);
                tvLoad.setVisibility(VISIBLE);
                content.setText("");
                startCountdown();
                getWearChatMessages(selectedCrop);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // 未选择时的处理
            }
        });

    }


    // 在Activity/Fragment中实现
    private Disposable disposable; // 用于控制订阅生命周期

    private void startCountdown() {
        if (disposable != null ) {
            disposable.dispose(); // 防止内存泄漏
            disposable = null;
        }
        // 倒计时总时长
        disposable = Observable.intervalRange(0, count + 1, 0, 1, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io()) // 在IO线程执行计时
                .observeOn(AndroidSchedulers.mainThread()) // 在主线程更新UI
                .map(aLong -> count - aLong) // 将递增值转为递减倒计时
                .subscribe(
                        remaining -> {
                            // 每秒更新UI（例如显示在TextView）
                            tvLoad.setText("AI助手正在思考中..."+remaining);

                        },
                        Throwable::printStackTrace, // 错误处理
                        () -> {
                            tvLoad.setVisibility(GONE);
                        }
                );
    }
    public void getWearChatMessages(String varietyName) {
        RxHttpUtils.
                createApi(BaseApi.class).getAiDetail("Bearer "+token, getAiDetail(varietyName))
                .compose(Transformer.switchSchedulers(null))
                .subscribe(new MDataObserver<AiWeatherRes>() {


                    @Override
                    protected void onSuccess(AiWeatherRes data) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (disposable != null ) {
                                disposable.dispose(); // 防止内存泄漏
                                disposable = null;
                            }
                            tvLoad.setVisibility(GONE);
                            if(data!=null){
                                content.setText(data.getMarkdownContent());
                                markwon.setMarkdown(content, data.getMarkdownContent());
                            }else {
                                content.setText("暂未获取到有效数据");
                            }
                        }
                    });
                    }
                });

    }
    private RequestBody getAiDetail(String varietyName) {
        JSONObject jb = new JSONObject();
        try {

            jb.put("province", province);
            jb.put("city", city);
            jb.put("county", county);
            jb.put("varietyName", varietyName);
            jb.put("user", user);

        } catch (JSONException e) {
            e.printStackTrace();
        }
        return getRequestBody(jb);
    }
    public   RequestBody getRequestBody(JSONObject jb) {
        return RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jb.toString());
    }
    
    // 添加窗口焦点变化监听
    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            getWindow().getDecorView().setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
        }
    }
}